package com.jijs.framework.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jijs.framework.dao.BaseDaoI;
import com.jijs.framework.model.EasyUIComboTree;
import com.jijs.framework.model.pmodel.AdeDictionary;
import com.jijs.framework.model.tmodel.TadeDictionary;
import com.jijs.framework.util.StringUtil;

/**
 * 数据字典
 * 
 * @author jijs
 * 
 */
@Service
public class DictionaryManagerService {

    @Autowired
    private BaseDaoI<TadeDictionary> dictionaryDao;

    /**
     * 后台管理的DataGrid
     * 
     * @param dictionary
     *            查询条件
     * @return
     */
    public List<AdeDictionary> dataGrid(AdeDictionary dictionary) {
        String hql = " from TadeDictionary t order by t.dictSort asc ";
        List<AdeDictionary> list = new ArrayList<AdeDictionary>();
        List<TadeDictionary> listt = dictionaryDao.find(hql);
        if (listt != null && listt.size() > 0) {
            for (TadeDictionary tAdmDictionary : listt) {
                AdeDictionary ad = new AdeDictionary();
                BeanUtils.copyProperties(tAdmDictionary, ad);
                list.add(ad);
            }
        }
        return list;
    }

    public String add(AdeDictionary dictionary) throws Exception {

        // 判断字典名称是否存在
        if (checkDuplicateField("dictName", dictionary.getDictName(), null)) {
            return "已经存在相同的【字典名称】，请修改！";
        }

        // 判断字典编号是否存在
        if (checkDuplicateField("dictCode", dictionary.getDictCode(), null)) {
            return "已经存在相同的【字典编号】，请修改！";
        }

        // 保存TAdmDictionary
        TadeDictionary t = new TadeDictionary();
        BeanUtils.copyProperties(dictionary, t);
        dictionaryDao.save(t);

        return null;
    }

    public String edit(AdeDictionary dictionary, String dictType) throws Exception {

        TadeDictionary t = dictionaryDao.get(TadeDictionary.class, dictionary.getId());

        if (!dictType.equals(t.getDictType())) {
            return "该字典项目的字典类型与参数中的不符，无法编辑！";
        }

        // 判断字典名称是否存在
        if (checkDuplicateField("dictName", dictionary.getDictName(), dictionary.getId())) {
            return "已经存在相同的【字典名称】，请修改！";
        }

        // 判断字典编号是否存在
        if (checkDuplicateField("dictCode", dictionary.getDictCode(), dictionary.getId())) {
            return "已经存在相同的【字典编号】，请修改！";
        }

        // 保存TAdmDictionary
        BeanUtils.copyProperties(dictionary, t);
        dictionaryDao.update(t);

        return null;
    }

    /**
     * 获取文件分类 树列表
     * 
     * @param excapeId
     *            例外ID，当该ID不为空的时候，去除此ID
     * 
     * @param docClassify
     * @return
     */
    public List<EasyUIComboTree> dictionarysComboTree(String excapeId) {

        String sql = " from TadeDictionary t order by t.dictSort asc ";

        List<EasyUIComboTree> dictionaryList = new ArrayList<EasyUIComboTree>();

        List<TadeDictionary> list = dictionaryDao.find(sql);

        if (list == null || list.size() == 0) {
            return dictionaryList;
        }

        for (TadeDictionary t : list) {
            if (t.getId().equals(excapeId)) {
                continue;
            }

            EasyUIComboTree tree = new EasyUIComboTree();
            tree.setId(t.getId());
            tree.setText(t.getDictName());

            if (null != t.getDictPid()) {
                tree.setPid(t.getDictPid());
            }
            dictionaryList.add(tree);
        }

        return dictionaryList;
    }

    /**
     * 删除字典项<br>
     * 如果字典项存在子节点，则提示无法删除<br>
     * 当返回null的时候，表示删除成功
     * 
     * @param id
     * @param dictType
     *            字典类型，表示删除的是用户字典还是系统字典
     * @return
     */
    public String delete(String id, String dictType) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("pid", id);
        long count = dictionaryDao.count("select count(*) from TadeDictionary t where t.dictPid = :pid", params);
        if (count != 0) {
            return "存在子节点，无法删除上级字典项目，请删除所有子节点后重试！";
        }

        TadeDictionary t = dictionaryDao.get(TadeDictionary.class, id);

        if (!dictType.equals(t.getDictType())) {
            return "找到了对应的字典项，但是该字典项目的字典类型与参数中的不符，无法删除！";
        }

        dictionaryDao.delete(t);
        return null;
    }

    /**
     * 根据ID获得对象
     * 
     * @param id
     * @return
     */
    public AdeDictionary getDictionary(String id) {

        AdeDictionary dictionary = new AdeDictionary();

        TadeDictionary t = dictionaryDao.get(TadeDictionary.class, id);
        BeanUtils.copyProperties(t, dictionary);

        return dictionary;
    }

    /**
     * 根据字典编码获取所有的字典数据
     * 
     * @author lihf
     * @date 2015年12月11日 下午4:43:26
     * @param dictCode
     * @return
     * @throws Exception
     */
    public AdeDictionary getDictionaryByDictCode(String dictCode) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("dictCode", dictCode);
        String hql = " from TadeDictionary t where 1=1 and t.dictCode=:dictCode ";
        AdeDictionary dict = new AdeDictionary();
        TadeDictionary t = dictionaryDao.get(hql, params);
        if (null != t) {
            BeanUtils.copyProperties(t, dict);
        }
        return dict;
    }

    /**
     * 根据父ID查找字典列表
     * 
     * @author lihf
     * @date 2016年1月14日 上午9:31:46
     * @param pid
     * @return
     * @throws Exception
     */
    private List<AdeDictionary> getByPid(String pid) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("dictPid", pid);
        String hql = " from TadeDictionary t where t.dictPid = :dictPid order by t.dictCode asc";
        List<TadeDictionary> list = dictionaryDao.find(hql, params);
        List<AdeDictionary> lista = null;
        if (list != null && list.size() > 0) {
            lista = new ArrayList<AdeDictionary>();
            for (TadeDictionary admDictionarys : list) {
                AdeDictionary admDictionary = new AdeDictionary();
                BeanUtils.copyProperties(admDictionarys, admDictionary);
                lista.add(admDictionary);

            }
        }
        return lista;
    }

    /**
     * 根据字典编码获取字典树
     * 
     */
    public List<AdeDictionary> getDictsByTypeCode(String dictCode) {
        AdeDictionary dict = getDictionaryByDictCode(dictCode);
        if (null == dict) {
            return new ArrayList<AdeDictionary>();
        }

        return getByPid(dict.getId());
    }

    /**
     * 校验字段是否重复
     * 
     * @author jijs
     * @date 2017-4-7
     * 
     * @param field
     *            要校验的字段
     * @param value
     *            值
     * @param id
     *            是否为修改。如果id值为null，则表示为添加；id不为null，则表示为修改。修改的时候不对自身进行判断
     * @return true 没有重复数据
     * @return false 存在重复数据
     */
    private boolean checkDuplicateField(String field, String value, String id) {

        Map<String, Object> params = new HashMap<String, Object>();

        StringBuffer hql = new StringBuffer();
        hql.append("select count(*) from TadeDictionary t where t.");
        hql.append(field);
        hql.append(" = :value");
        params.put("value", value);

        if (StringUtil.isNotEmpty(id)) {
            hql.append(" and id != :id");
            params.put("id", id);
        }

        long result = dictionaryDao.count(hql.toString(), params);

        return result != 0;
    }
}
